package book.zone.model;

import book.zone.helpers.PasswordCrypt;
import book.zone.log.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created by IntelliJ IDEA.
 * User: neveragny
 * Date: 19.05.2010
 * Time: 0:27:19
 */
public class SignInModel{

    private String[] matchUserDetails(String email){
        String[] credentials = new String[2];
        String selectStatement = "SELECT * FROM USERS "
                                + "WHERE email="
                                + "'" + email + "'";
//        Logger.out(selectStatement);

        try{
            Context ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/bookzone");
            if (ds != null) {
                Connection conn = ds.getConnection();
                if(conn != null){
//                    Logger.out("Got Connection " + conn.toString());
                    Statement stmt = conn.createStatement();
                    ResultSet rst = stmt.executeQuery(selectStatement);
                    if(rst.next()){
                    //////DEBUG//////////
//                    Logger.out("ResultSet.email: " + rst.getString("email"));
//                    Logger.out("ResultSet.passwd: " + rst.getString("passwd"));
                    /////////////////
                        credentials[0] = rst.getString("email");
                        credentials[1] = rst.getString("passwd");
                    }
                    stmt.close();
                    conn.close();
                }
            }
            else{
                Logger.out("Not Connected. Check in SignInModel");
            }
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return credentials;
    }

    /*
     * Some method that control this instance.
     */
    public boolean doMatch(String email, String passwd){
        String[] creds = this.matchUserDetails(email);
        //
//        Logger.out("PasswordCrypt.encrypt(passwd)  "+PasswordCrypt.encrypt(passwd));
//        Logger.out("creds[1]" + creds[1]);
        //
        return PasswordCrypt.encrypt(passwd).equals(creds[1]);
    }
}
